package com.xxx.springboot.filter;

import com.xxx.springboot.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 1.mdc日志链路追踪过滤器
 * @author guwq
 * @since 2021/6/29
 */
@Slf4j
@WebFilter(filterName = "mdcFilter", urlPatterns = "/*", servletNames = "*")
@Order(1)
public class MdcFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init web container......");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 设置全局唯一标识traceId，此处以UUID为唯一标识
        MDC.put("traceId", UUIDUtils.createUUID16());
        chain.doFilter(request, response);
        // 清除标识
        MDC.remove("traceId");
    }

    @Override
    public void destroy() {
        log.info("destroy web container......");
    }
}
